from django.contrib import admin
from .models import AlarmRecord

@admin.register(AlarmRecord)
class AlarmRecordAdmin(admin.ModelAdmin):
    """报警记录管理"""
    list_display = [
        'created_at',
        'subscription_type',
        'get_data_source_name',
        'get_identifier',
        'value',
        'message',
        'acknowledged',
        'acknowledged_by',
        'acknowledged_at'
    ]
    list_filter = [
        'created_at',
        'subscription_type',
        'acknowledged',
        ('opcua_subscription__data_source', admin.RelatedOnlyFieldListFilter),
        ('mqtt_subscription__data_source', admin.RelatedOnlyFieldListFilter)
    ]
    search_fields = [
        'message',
        'opcua_subscription__node_id',
        'mqtt_subscription__topic',
        'opcua_subscription__data_source__name',
        'mqtt_subscription__data_source__name'
    ]
    date_hierarchy = 'created_at'
    ordering = ['-created_at']
    readonly_fields = [
        'subscription_type',
        'opcua_subscription',
        'mqtt_subscription',
        'value',
        'message',
        'created_at'
    ]

    def get_data_source_name(self, obj):
        """获取数据源名称"""
        return obj.get_data_source_name()
    get_data_source_name.short_description = '数据源'
    get_data_source_name.admin_order_field = 'opcua_subscription__data_source__name'

    def get_identifier(self, obj):
        """获取标识符（节点ID或主题）"""
        return obj.get_identifier()
    get_identifier.short_description = '标识符'
    get_identifier.admin_order_field = 'opcua_subscription__node_id'

    def has_add_permission(self, request):
        """禁止手动添加报警记录"""
        return False

    def has_delete_permission(self, request, obj=None):
        """禁止删除报警记录"""
        return False

    def get_actions(self, request):
        """移除删除操作"""
        actions = super().get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions
